/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.infodb.data.web;

import com.alibaba.fastjson.JSONObject;
import com.hyts.infodb.data.bean.vo.DataDTO;
import com.hyts.infodb.enums.SystemConfiguration;
import com.hyts.infodb.task.bean.TaskModel;
import com.hyts.infodb.task.config.AsyncTaskConfiguration;
import com.hyts.infodb.task.handler.AsyncTaskHandler;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @project-name:infodb
 * @package-name:com.hyts.infodb.data.web
 * @author:LiBo/Alex
 * @create-date:2020-02-23 12:01
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@Api("异步数据中心")
@Slf4j
@RestController
@RequestMapping("/async")
public class AsyncDataController {


    @Autowired
    RestTemplate restTemplate;

    /**
     * Rigorous Test :-)
     */
    @Autowired
    AsyncTaskHandler asyncTaskHandler;



    @GetMapping("/execute/{taskNode}")
    public DataDTO execute(@PathVariable String taskNode, @RequestParam String param){
        return executeInternal(new TaskModel<>(taskNode,param));
    }


    @PostMapping("/execute")
    public DataDTO execute(@RequestBody TaskModel taskModel){
        return executeInternal(taskModel);
    }

    /**
     * 执行内部方法
     * @param taskModel
     * @return
     */
    private DataDTO executeInternal(TaskModel taskModel){
        CompletableFuture completableFuture = (CompletableFuture) asyncTaskHandler.execute(taskModel);
        DataDTO dataDTO = new DataDTO();
        try {
            Object result = completableFuture.get(AsyncTaskConfiguration.MAX_WAIT_SECONDS, TimeUnit.SECONDS);
            return (DataDTO) dataDTO.success(SystemConfiguration.MessageConfiguration.EXECUTE,"task",result);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            log.error("异步服务调用失败!",e);
            return (DataDTO) dataDTO.failure(SystemConfiguration.MessageConfiguration.EXECUTE,"task");
        }
    }
}
